package com.rjt.article.util;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;


@Controller
@RequestMapping("/ueditor/")
public class UEditorDealUtil {
	//从配置文件获取图片的上传路径及访问的信息
	@Value("${UEditor.picPath}")
	private String picPath;
	@Value("${UEditor.hostUrl}")
	private String hostUrl;
	@Value("${UEditor.picSize}")
	private int picSize;
	@RequestMapping(value = "jsp/controller")
	@ResponseBody
	public String ueditor(HttpServletRequest request, HttpServletResponse response) {

	    String s = "{\n"+
	           "            \"imageActionName\": \"uploadimage\",\n" +
	           "                \"imageFieldName\": \"file\", \n" +
	           "                \"imageMaxSize\": 3072000, \n" +
	           "                \"imageAllowFiles\": [\".png\", \".jpg\", \".jpeg\", \".gif\", \".bmp\"], \n" +
	           "                \"imageCompressEnable\": true, \n" +
	           "                \"imageCompressBorder\": 1600, \n" +
	           "                \"imageInsertAlign\": \"none\", \n" +
	           "                \"imageUrlPrefix\": \"\",\n" +
	           "                \"imagePathFormat\": \"/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}\" }";
	    return s;

	}
	@RequestMapping(value = "/imgUpdate")
	@ResponseBody
	public String imgUpdate(@RequestParam("file") MultipartFile file,HttpServletRequest request) {
	    if (file.isEmpty()) {
	        return "{\"state\": \"上传的图片为空\"}";
	    }else if (file.getSize()>picSize*1024) {
	    	return "{\"state\": \"上传的图片大于"+(picSize/1024)+"m\"}";
	    }
	    // 获取文件名
	    String fileName = file.getOriginalFilename();
	    // 获取文件的后缀名
	    String suffixName = fileName.substring(fileName.lastIndexOf("."));
	    // 这里我使用随机字符串来重新命名图片
	    fileName = Calendar.getInstance().getTimeInMillis() + suffixName;
	    File dest = new File(picPath + fileName);
	    // 检测是否存在目录
	    if (!dest.getParentFile().exists()) {
	        dest.getParentFile().mkdirs();
	    }
	    try {
	        file.transferTo(dest);
	        String url=hostUrl+"/image/";
	        //TODO url要改
	        String config ="{\"state\": \"SUCCESS\"," +
	                "\"url\": \"" +url  + fileName + "\"," +
	                "\"title\": \"" + fileName + "\"," +
	                "\"original\": \"" + fileName + "\"}";
	        return config;
	    } catch (IllegalStateException e) {
	        e.printStackTrace();
	    } catch (IOException e) {
	        e.printStackTrace();
	    }
	    return "{\"state\": \"未知错误\"}";
	}
	
    
    
}
